package com.chuanyang.driverh.mainother;


import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.overlay.DrivingRouteOverlay;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.chuanyang.driverh.BaseApplication;
import com.chuanyang.driverh.R;
import com.chuanyang.driverh.amap.AMapUtil;
import com.chuanyang.driverh.amap.LocationEntity;
import com.chuanyang.driverh.base.BaseTitleActivity;
import com.chuanyang.driverh.responseresult.LoadUnloadGuideStateResult;
import com.chuanyang.driverh.responseresult.OrderAddressData;
import com.chuanyang.driverh.responseresult.OrderAddressResult;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.LogUtils;
import com.chuanyang.driverh.utils.PermissoinUtil;
import com.chuanyang.driverh.utils.PrintUtil;
import com.chuanyang.driverh.utils.SharedPrefUtil;
import com.chuanyang.driverh.utils.net.JsonGenericsSerializator;
import com.chuanyang.driverh.utils.net.MyCallback;
import com.chuanyang.driverh.utils.net.MyHttpUtil;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

public class BeforeNaviActivity extends BaseTitleActivity implements RouteSearch.OnRouteSearchListener,AMap.OnCameraChangeListener {
    private TextView tv_beforenavi_loadgood;
    private TextView tv_beforenavi_unloadgood;
    private FrameLayout fl_beforenavi_startnavi;
    private ImageView iv_my_location;
    private MapView mv_before_navi;
    private MapView mapView;
    private AMap amap;
    private LatLng latLng=new LatLng(119.388051,35.174727);
    private float zoom=15;
    private boolean haswizard = false;//默认没有装卸货向导
    private OrderAddressData startAddress;
    private OrderAddressData endAddress;
    private LocationEntity locationEntity;

    private RouteSearch routeSearch;
    private DriveRouteResult driveRouteResult;

    private boolean isCongestion;
    private boolean isCost;
    private boolean isHightspeed;
    private boolean isDirect;
    private boolean isAvoidhightspeed;

    private int endAddrType;//导航的目的地，0订单起始地，1，订单目的地。

    @Override
    protected int getContentResId() {
        return R.layout.other_act_beforenavi;
    }
    @Override
    protected void initView(Bundle savedInstanceState) {
        mapView = (MapView) findViewById(R.id.mv_before_navi);
        mapView.onCreate(savedInstanceState); // 此方法必须重写
        if(amap==null){
            amap=mapView.getMap();
            setMapUI();
            AMapUtil.moveToLatLng(amap,latLng,zoom);
        }

        tv_beforenavi_loadgood=(TextView)findViewById(R.id.tv_beforenavi_loadgood);
        tv_beforenavi_unloadgood=(TextView)findViewById(R.id.tv_beforenavi_unloadgood);
        fl_beforenavi_startnavi=(FrameLayout)findViewById(R.id.fl_beforenavi_startnavi);
        mv_before_navi=(MapView)findViewById(R.id.mv_before_navi);
        iv_my_location=(ImageView) findViewById(R.id.iv_my_location);
    }
    private void setMapUI(){
        UiSettings uiSettings = amap.getUiSettings();
        uiSettings.setScaleControlsEnabled(false);  //不显示比例尺amap
        uiSettings.setZoomControlsEnabled(true);
        uiSettings.setTiltGesturesEnabled(false);   //关闭手势倾斜和滑动
        uiSettings.setRotateGesturesEnabled(false);

        uiSettings.setMyLocationButtonEnabled(false); // 是否显示默认的定位按钮
        amap.setMyLocationEnabled(true);// 是否可触发定位并显示定位层
        amap.setOnCameraChangeListener(this);
    }

    @Override
    protected void initData() {

        setBackImg();
        getTitleTextView().setText("导航");
        getRightTextView().setText("策略");

        locationEntity= BaseApplication.getInstance().getLocationEntity();
        if (locationEntity!=null && locationEntity.getLongitude()!=0){
            latLng=new LatLng(locationEntity.getLatitude(),locationEntity.getLongitude());
            AMapUtil.moveToLatLng(amap,latLng,zoom);
        }else{
            getPermission();
            BaseApplication.getInstance().startLoc();
            PrintUtil.toast(activityContext,"请检查定位权限");
            finish();
            return;
        }
        getStrategy();
        routeSearch = new RouteSearch(this);
        routeSearch.setRouteSearchListener(this);
        getIntentData();

    }


    private void getPermission() {
        try {
            PermissoinUtil.checkAndRequestPermissions(activityContext, new String[]{
                    android.Manifest.permission.ACCESS_FINE_LOCATION,
                    android.Manifest.permission.ACCESS_COARSE_LOCATION,
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    @Override
    protected void initListener() {
        iv_my_location.setOnClickListener(this);
        tv_beforenavi_loadgood.setOnClickListener(this);
        tv_beforenavi_unloadgood.setOnClickListener(this);
        fl_beforenavi_startnavi.setOnClickListener(this);
        getLoadUnloadGuideState();
    }

    /**
     * 右侧的按钮事件
     */
    protected void baseGoEnsure() {
        Intent intent1 = new Intent(this, StrategyActivity.class);
        startActivity(intent1);

    }


    private void getStrategy() {
        isCongestion = SharedPrefUtil.isCongestion();
        //避免收费
        isCost = SharedPrefUtil.isCost();
        //高速优先
        isHightspeed = SharedPrefUtil.isHightspeed();
        //避免高速
        isAvoidhightspeed = SharedPrefUtil.isAvoidhightspeed();
        //直接导航
        isDirect = SharedPrefUtil.isDirect();
    }

    /**
     * 获取从从上个页面传递来的途经点信息
     */
    private void getIntentData() {
        OrderAddressResult orderAddress = (OrderAddressResult) (getIntent().getSerializableExtra("OrderAddressResult"));
        //获取此时装卸货向导状态  ，存在装卸货向导则直接通过其状态判断是去装货还是卸货             //如果不存在装卸货向导，则让司机选择是卸货还是装货
        if (orderAddress.getData() != null && orderAddress.getData().size() > 0) {
            OrderAddressData addressData = orderAddress.getData().get(0);
            if (addressData.getWizardId() != null) {
//                wizardId = addressData.getWizardId();
                haswizard = true;
            }
            //分别获取途经点的起点和终点
            for (OrderAddressData orderAddressData : orderAddress.getData()) {
                if (orderAddressData.getPointType().equals("s")) {
                    startAddress = orderAddressData;
                } else if (orderAddressData.getPointType().equals("e")) {
                    endAddress = orderAddressData;
                }
            }
        }
    }
    /**
     * 开始搜索路径规划方案
     */
    public void searchRouteResult(LatLonPoint startPoint1, LatLonPoint endPoint1) {
        getStrategy();
        int strategy=0;
        if(isCongestion){
            strategy= RouteSearch.DrivingAvoidCongestion;
        }else if(isCost){
            strategy= RouteSearch.DrivingSaveMoney;
        }else if(isAvoidhightspeed){
            strategy= RouteSearch.DrivingNoHighWaySaveMoney;
        }else {
            strategy= RouteSearch.DrivingDefault;
        }
        if(startPoint1==null || endPoint1==null)
            return;
        final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(startPoint1, endPoint1);
        RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo,strategy,
                null, null, "");// 第一个参数表示路径规划的起点和终点，第二个参数表示驾车模式，第三个参数表示途经点，第四个参数表示避让区域，第五个参数表示避让道路
        routeSearch.calculateDriveRouteAsyn(query);// 异步路径规划驾车模式查询
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_my_location:
                locationEntity= BaseApplication.getInstance().getLocationEntity();
                AMapUtil.moveToLatLng(amap,new LatLng(locationEntity.getLatitude(),locationEntity.getLongitude()),zoom);
                break;
            case R.id.tv_beforenavi_loadgood:
                endAddrType=0;
                if (startAddress != null) {
                    tv_beforenavi_loadgood.setSelected(true);
                    tv_beforenavi_unloadgood.setSelected(false);

                    if (Double.valueOf(startAddress.getLatitude())>90){
                        searchRouteResult(new LatLonPoint(latLng.latitude, latLng.longitude),
                                new LatLonPoint(Double.valueOf(startAddress.getLongitude()),Double.valueOf(startAddress.getLatitude())));
                    }else {
                        searchRouteResult(new LatLonPoint(latLng.latitude, latLng.longitude),
                                new LatLonPoint(Double.valueOf(startAddress.getLatitude()),Double.valueOf(startAddress.getLongitude())));
                    }

                }
                break;
            case R.id.tv_beforenavi_unloadgood:
                endAddrType=1;
                if (endAddress != null) {
                    tv_beforenavi_loadgood.setSelected(false);
                    tv_beforenavi_unloadgood.setSelected(true);
                    if (Double.valueOf(endAddress.getLatitude())>90){
                        searchRouteResult(new LatLonPoint(latLng.latitude, latLng.longitude),
                                new LatLonPoint(Double.valueOf(endAddress.getLongitude()),Double.valueOf(endAddress.getLatitude())));
                    }else {
                        searchRouteResult(new LatLonPoint(latLng.latitude, latLng.longitude),
                                new LatLonPoint(Double.valueOf(endAddress.getLatitude()),Double.valueOf(endAddress.getLongitude())));
                    }

                }
                break;
            case R.id.fl_beforenavi_startnavi:
                Intent intent = new Intent(this, GpsNaviActivity.class);

                if (endAddrType==0){
                    intent.putExtra("endlongtitude", Double.valueOf(startAddress.getLongitude()));
                    intent.putExtra("endlatitude", Double.valueOf(startAddress.getLatitude()));
                }else{
                    intent.putExtra("endlongtitude", Double.valueOf(endAddress.getLongitude()));
                    intent.putExtra("endlatitude", Double.valueOf(endAddress.getLatitude()));
                }
                startActivity(intent);
                break;
            default:
                break;
        }
    }




    /**
     * 获取装卸货向导的状态
     */
    private void getLoadUnloadGuideState() {
        Map<String,String> params=new HashMap<String, String>();
        params.put("waybillId", 1314 + "");
        params.put("wizardId", 3 + "");
        MyHttpUtil.getLoadUnloadGuideState(activityContext,params, new MyCallback<LoadUnloadGuideStateResult>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                tv_beforenavi_loadgood.performClick();
            }
            @Override
            public void onSuccess(LoadUnloadGuideStateResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                     int  currentState = result.getData().getState();
                    if (currentState < 4) {
                        if (startAddress != null) {
                            tv_beforenavi_loadgood.performClick();
                        }
                    } else {
                        if (endAddress != null) {
                            tv_beforenavi_unloadgood.performClick();
                        }
                    }
                }else{
                    tv_beforenavi_loadgood.performClick();
                }
            }
        });
    }





    //地图的生命周期方法
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        mapView.onDestroy();
        super.onDestroy();
    }

    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {
        LogUtils.d("bus");
    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult result, int rCode) {
        if (rCode == 1000) {
            if (result != null && result.getPaths() != null
                    && result.getPaths().size() > 0) {
                driveRouteResult = result;
                DrivePath drivePath = driveRouteResult.getPaths().get(0);
                amap.clear();// 清理地图上的所有覆盖物
                AMapUtil.setMyLocationStyle(amap);
                DrivingRouteOverlay drivingRouteOverlay = new DrivingRouteOverlay(
                        this, amap, drivePath, driveRouteResult.getStartPos(),
                        driveRouteResult.getTargetPos());
                drivingRouteOverlay.removeFromMap();
                drivingRouteOverlay.addToMap();
                drivingRouteOverlay.zoomToSpan();
                drivingRouteOverlay.setNodeIconVisibility(false);
            } else {
                PrintUtil.toast(this, "没搜到规划结果");
            }
        } else if (rCode == 27) {
            PrintUtil.toast(this, "网络异常");
        } else if (rCode == 32) {
            PrintUtil.toast(this, "key异常");
        } else {
//            PrintUtil.toast(this, "其他异常" + rCode);
        }

    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {
        LogUtils.d("walk");
    }

    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {
        LogUtils.d("ride");
    }


    @Override
    public void onCameraChange(CameraPosition cameraPosition) {

    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        zoom=cameraPosition.zoom;
    }
}
